<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

class CoreSession {
	var $session_id;
	var $session_starttime;
	var $session_timeout;
	var $session_currenttime;
	var $session_content = array();
	
	var $session_mode;
	
	var $user_id;				//user
	var $user_ip;				//ip
	var $user_location;			//current url
	var $user_info = array();	//profile
	
	//constructor
	function CoreSession() {
		$this->session_id = $this->getSessionId();
	}
	
	function getSessionId() {
		if( SID == '' ) {
			$this->session_mode = 'cookie';
		}
		
		$this->session_id = session_id();
		return $this->session_id;
	}
	
	function getSessionContent() {
		return $this->session_content;
	}
	
	function getUserId() {
		return $this->user_id;
	}
	
	function getUserIp() {
		return $this->_get_ip_address();
	}
	
	function getUserLocation() {
		return $this->user_location;
	}
	
	function getUserInfo() {
		return $this->user_info;
	}
	
	//methods
	function getCookieData($key) {
		if( isset($_COOKIE[$key]) ) {
			return $_COOKIE[$key];
		}
		return false;
	}
	
	function setCookieData($name, $value, $permanent = true) {
		$cookie_name = $name;
		//
		$cookie_duration = 60 * 60 * 24 * 365;
		if( $permanent ) {
			$cookie_expire = $this->session_currenttime + $cookie_duration;
		} else {
			$cookie_expire = 0;
		}
		
		setcookie($cookie_name, $value, $cookie_expire, COOKIE_PATH, COOKIE_DOMAIN, COOKIE_SECURE);
	}
	
	function setSessionValue($key, $value) {
		$this->session_content[$key] = $value;
	}
	
	function getSessionValue($key) {
		if( isset($this->session_content[$key]) ) {
			return $this->session_content[$key];
		}
		return '';
	}
	
	function delSessionValue($key) {
		if( isset($this->session_content[$key]) ) {
			unset($this->session_content[$key]);
		}
	}
	
	function cleanSessionValue() {
		if( isset($this->session_content) ) {
			unset($this->session_content);
		}
	}
	
	//private
	function _get_ip_address() {
		$ip_address = '';
		if( $_SERVER['REMOTE_ADDR'] ) {
			$ip_address = $_SERVER['REMOTE_ADDR'];
		} elseif( $_ENV['REMOTE_ADDR'] ) {
			$ip_address =  $_ENV['REMOTE_ADDR'];
		} else {
			$ip_address = getenv("REMOTE_ADDR");
		}
		$ip_address = preg_replace("/[^\.0-9]+/", "", $ip_address);
		
		return $ip_address;
	}

}
//
?>